package com.fast.fast.upms.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fast.fast.common.base.exception.BizException;
import com.fast.fast.upms.api.entity.SysRolePerm;
import com.fast.fast.upms.api.entity.SysUserRole;
import com.fast.fast.upms.biz.base.util.ClearAuthUtils;
import com.fast.fast.upms.biz.mapper.SysRolePermMapper;
import com.fast.fast.upms.biz.service.SysRolePermService;
import com.fast.fast.upms.biz.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lyf
 * @description 针对表【sys_role_perm(系统角色权限关联表)】的数据库操作Service实现
 * @createDate 2022/01/01 00:00 周六
 */
@Service
public class SysRolePermServiceImpl extends ServiceImpl<SysRolePermMapper, SysRolePerm>
        implements SysRolePermService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private ClearAuthUtils clearAuthUtils;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addPerms(Long roleId, List<?> permIds) {
        if (ObjectUtil.isEmpty(roleId)) {
            throw new BizException("角色id不能为空");
        }

        // 删除系统角色权限关联表数据
        List<Long> ids = list(Wrappers.lambdaQuery(SysRolePerm.class)
                .eq(SysRolePerm::getRoleId, roleId)
        ).stream().map(SysRolePerm::getId).collect(Collectors.toList());
        removeBatchByIds(ids);

        List<SysRolePerm> sysRolePerms = permIds.stream().map(o -> {
            SysRolePerm sysRolePerm = new SysRolePerm();
            sysRolePerm.setRoleId(roleId);
            sysRolePerm.setPermId(Long.valueOf((String) o));
            return sysRolePerm;
        }).collect(Collectors.toList());
        saveBatch(sysRolePerms);

        // 获取该角色下的所有用户id
        List<Long> sysUserIds = sysUserRoleService.list(Wrappers.lambdaQuery(SysUserRole.class)
                .eq(ObjectUtil.isNotEmpty(roleId), SysUserRole::getRoleId, roleId)
        ).stream().map(SysUserRole::getUserId).collect(Collectors.toList());
        // 清除指定用户的权限编码集合
        clearAuthUtils.clearSpecifiedUserPermList(sysUserIds);
        return true;
    }
}




